// index.js
// 获取应用实例
const app = getApp();
// app.globalData.indexJS = _that;

Page({
  data: {
    // telphone: '15229883888',
    telArr: [],
    openId: '',
    total: '0',
    haveNumber: '0',
    endNumber: '0',
    sq: '0',
    jg: '0',
    cw: '0',
    deptIds: [],
    // setInterval: '',
    showModal: false,
    quxiao: true,
    showGetPhone: false,
    showUser: false,
    addRouter: '',
    deptIds2: [],
    admin: 0,
    subAdmin: 0,
    inDept: false,
    noticeNumber: 0,
    agreementShow: false,
    tellShow: false,
    userPhone: ''
  },

  onLoad() {
    // this.data.setInterval = setInterval(() => {
    //   this.getDepartmentList();
    //   this.getReimbursement();
    // }, 2000);
    wx.hideShareMenu();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (app.globalData.loginPromise) {
      app.globalData.loginPromise.then(() => {
        this.init();
      })
    } else {
      this.init();
    }
    
  },

  init() {
    this.getphone();
    this.haveNotice();
    if (wx.getStorageSync('token')) {
      this.getAdmin();
    }
    if (wx.getStorageSync('userPhone')) {
      this.setData({
        userPhone: wx.getStorageSync('userPhone')
      });
      this.getDepartmentList();
      this.getReimbursement();
    } else {
      this.setData({
        userPhone: ''
      });
    }
  },

  haveNotice() {
    wx.request({
      url: `${app.globalData.baseUrl}/api/notice/noticeNumber`,
      method: "GET",
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      success: (res) => {
        if (res.data.code == 0) {
          this.setData({
            noticeNumber: res.data.data
          });
        }
      }
    })
  },

  notifications(e) {
    // if (!wx.getStorageSync('userPhone')) {
    //   this.setData({ showGetPhone: true });
    //   return;
    // }
    if (this.data.inDept || this.data.admin == 1 || this.data.subAdmin == 1) {
      wx.navigateTo({
        url: `/pages/notifyList/index?status=${e.currentTarget.dataset.status}&edit=${this.data.admin == 1 || (this.data.subAdmin == 1 && e.currentTarget.dataset.status == 1) ? 'yes' : 'no'}`,
      });
    } else {
      wx.showModal({
        title: '您不是部门处理人',
        showCancel: false
      });
    }
  },
  // 获取部门列表
  getDepartmentList() {
    wx.request({
      url: `${app.globalData.baseUrl}/api/finance/getUserDept`,
      method: "GET",
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      success: (res) => {
        if (res.data.code == 0) {
          const deptIds = [];
          const deptIds2 = [];
          res?.data?.data?.forEach(item => {
            deptIds.push(item.deptId);
            if (item.deptId < 4) {
              deptIds2.push(item.deptId);
            }
          });
          const inDept = deptIds.indexOf(1) > -1 || deptIds.indexOf(2) > -1 || deptIds.indexOf(3) > -1 || deptIds.indexOf(10) > -1;
          console.log(deptIds2)
          this.setData({
            inDept,
            deptIds,
            deptIds2,
          });
        }
      }
    })
  },
  // 财务  TOO 财务审批列表
  GoAudit: function (e) {
    // if (!wx.getStorageSync('userPhone')) {
    //   this.setData({ showGetPhone: true });
    //   return;
    // }
    const id = e.currentTarget.dataset.status;
    if (!id) {
      wx.showModal({
        title: '您不在该部门',
        showCancel: false
      });
      return;
    }
    wx.navigateTo({
      url: `/pages/ReviewList/index?id=` + id
    });
  },

  getphone() {
    wx.request({
      url: `${app.globalData.baseUrl}/api/login/getContact`,
      method: "GET",
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      success: (res) => {
        let that = this;
        if (res.data.code == 0) {
          that.setData({
            telArr: res.data.data
          })
          this.childComponent = this.selectComponent("#loginInfo");
          this.childComponent.reset();
        }
      }
    })
  },

  // 获取报销流程数据
  getReimbursement() {
    wx.request({
      url: `${app.globalData.baseUrl}/api/finance/getFinanceStatistics`,
      method: "GET",
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      success: (res) => {
        let that = this;
        if (res.data.code == 0) {
          that.setData({
            total: res.data.data.total || 0,
            haveNumber: res.data.data.haveNumber || 0,
            endNumber: res.data.data.endNumber || 0,
            sq: res.data.data.sq || 0,
            jg: res.data.data.jc || 0,
            cw: res.data.data.cw || 0,
          })
          // clearInterval(that.data.setInterval);
        } else if (res.data.code == 401) { }
      }
    })
  },

  go: function () {
    // TOO  添加财务工单页面
    // const _that = this;
    // if (!wx.getStorageSync('userPhone')) {
    //   wx.removeStorage({
    //     key: 'financialData',
    //     success: function () {
    //       _that.setData({
    //         showGetPhone: true,
    //         addRouter: '/pages/addFinancialReimbursement/index'
    //       });
    //     }
    //   });
    //   return;
    // }
    if (!!wx.getStorageSync('financialData') && !!wx.getStorageSync('financialCommit')) {
      wx.removeStorage({
        key: 'financialData',
        success: function () {
          wx.navigateTo({
            url: '/pages/addFinancialReimbursement/index'
          })
        }
      })
    } else {
      wx.navigateTo({
        url: '/pages/addFinancialReimbursement/index'
      })
    }
  },

  bindDHShow() {
    this.setData({
      tellShow: true
    });
  },

  linkMenchuang() {
    wx.navigateToMiniProgram({
      appId: 'wx987c9d744798636f',
      path: '/pages/index/index',
      envVersion: 'release',
      success(res) {
        console.log(res)
      }
    })
  },

  closePhone(e) {
    this.setData({ showGetPhone: false });
    if (e.detail) this.setData({ showUser: true });
    this.init();
  },

  closeUser() {
    this.setData({ showUser: false });
  },

  setManage() {
    this.setData({
      agreementShow: false
    });
    wx.navigateTo({
      url: '/pages/acountCenter/index',
    });
  },

  setDemo() {
    wx.navigateTo({
      url: '/pages/demo/index',
    });
  },

  agreement() {
    this.setData({
      agreementShow: true
    });
  },

  closeModal() {
    this.setData({
      agreementShow: false
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  onPullDownRefresh() {
    this.init();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  },

  getAdmin() {
    wx.request({
      url: `${app.globalData.baseUrl}/api/accounting/selManage`,
      method: "GET",
      header: {
        'token': wx.getStorageSync('token'),
        "Content-Type": "application/json"
      },
      success: (res) => {
        if (res.data.code == 0) {
          const arr = [];
          const subArr = [];
          res.data.data?.forEach(item => {
            if (item.status === '1') arr.push(item.tel);
            if (item.status === '0') subArr.push(item.tel);
          });
          if (arr.indexOf(wx.getStorageSync('userPhone').toString()) > -1) {
            wx.setStorageSync('admin', 1);
            this.setData({
              admin: 1
            });
          } else {
            wx.setStorageSync('admin', 0);
            this.setData({
              admin: 0
            });
          };
          if (subArr.indexOf(wx.getStorageSync('userPhone').toString()) > -1) {
            wx.setStorageSync('subAdmin', 1);
            this.setData({
              subAdmin: 1
            });
          } else {
            wx.setStorageSync('subAdmin', 0);
            this.setData({
              subAdmin: 0
            });
          };
        } else {
          wx.showToast({
            title: res.data.msg || '出错啦！',
            icon: 'error',
            duration: 2000
          })
        }
      }
    })
  },

  linkmemorandum() {
    wx.navigateTo({
      url: '/pages/memorandum/index',
    });
  },

  onTellClose() {
    this.setData({
      tellShow: false
    });
  },

  onSelect(event) {
    const that = this;
    wx.makePhoneCall({
      phoneNumber: event.currentTarget.dataset.tel,
      success() {
        that.onTellClose();
      },
    })
  },

  copyText() {
    wx.setClipboardData({
      data: 'http://zhaishu.store/login',
      success: function (res) {
        wx.showToast({
          title: '复制成功',
        })
      }
    })
  },

  login() {
    this.setData({ showGetPhone: true });
  }
})